package FromDB;

import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.jdbc.JDBCCategoryDataset;

import DB.DBConnecter;

public class HistogramImage {
	
	public static void main(String[] args) {
		try {
			createSalaryPerFinanceEmployeeBarChart();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Create Bar Chart showing salary of each employee.
	 * 
	 *            Horizontal or Vertical orientation of bar chart.
	 * @return Bar Chart.
	 * @throws UnsupportedEncodingException 
	 */
	public static JFreeChart createSalaryPerFinanceEmployeeBarChart() throws UnsupportedEncodingException {

		JFrame frame = new JFrame("dbtest");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JFreeChart barChart =null;


		try {
			final String QUERY_SALARY_PER_FINANCE_EMPLOYEE = "SELECT S_DEPT.NAME, count(*) AS num_employees "
					+ "FROM S_DEPT, S_EMP "
					+ "WHERE S_EMP.DEPT_ID = S_DEPT.ID "
					+ "GROUP BY S_DEPT.NAME";

			final CategoryDataset barDataset = new JDBCCategoryDataset(
					DBConnecter.getConnection(),
					QUERY_SALARY_PER_FINANCE_EMPLOYEE);

			final String TITLE_SALARY_PER_FINANCE_EMP = "Employees Per Department";
			final String LABEL_EMPLOYEES_FINANCE = new String("X".getBytes("ISO-8859-1"), "UTF-8");
			final String LABEL_SALARIES =  new String("Y".getBytes("GBK"), "ISO-8859-1");
			barChart = ChartFactory.createBarChart(
					TITLE_SALARY_PER_FINANCE_EMP, // title
					LABEL_EMPLOYEES_FINANCE, // x-axis label
					LABEL_SALARIES, // y-axis label
					barDataset, PlotOrientation.VERTICAL, true, // legend displayed
					true, // tooltips displayed
					false); // no URLs
			BufferedImage image = barChart.createBufferedImage(750, 450);
			JLabel label = new JLabel();
			label.setIcon(new ImageIcon(image));
			frame.getContentPane().add(label);

			frame.pack();
			frame.setVisible(true);
		} catch (SQLException sqlEx) {
		}

		return barChart;
	}

}
